//
//  WmcPreferenceSettingsManager.swift
//  YPWatermarkCamera
//
//  Created by 周诗松 on 2022/5/5.
//

import Foundation
import RxSwift
import YPBedrock

class WmcPreferenceSettingsManager: NSObject {
    /// 单例实例化
    static let shared: WmcPreferenceSettingsManager = {
        let manager = WmcPreferenceSettingsManager()
        manager.loadCameraSettings() // 加载相机设置
        return manager
    }()

    /// 默认相机设置对象
    private(set) lazy var cameraSetting: WmcPreferenceCameraSettingsModel = .init()

    /// 同步配置列表
    private(set) var syncCongigList: [WmcMediaAlbumConfigurationModel]?

    /// 更新相机设置
    static func updateCameraSettings(model: WmcPreferenceCameraSettingsModel) {
        if let json = model.toJSON() {
            shared.cameraSetting = model
            WmcUserdefault.save(value: json, forKey: .Data.cameraSetting)
        }
    }
    
    /// 清除同步配置
    static func cleanSyncCongig() {
        WmcPreferenceSettingsManager.shared.syncCongigList = nil
    }

    /// 查询同步开关状态
    /// - Parameters:
    ///   - completion: 查询结果
    ///   - failure: 查询失败
    static func querySyncSwitchConfig(completion: @escaping ((isOpen: Bool, list: [WmcMediaAlbumConfigurationModel])) -> Void, failure: ((Error?) -> Void)? = nil) {
        WmcPreferenceSettingsManager.queryTeamSyncConfigCache { list in
            let isOpen = WmcPreferenceSettingsManager.shared.isNeedUpload(configList: list)
            let result = (isOpen: isOpen, list: list)
            completion(result)
        } failure: { error in
            failure?(error)
        }
    }

    /// 请求接口查询开启了同步的团队的个数
    /// - Parameters:
    ///   - success: 个数
    ///   - failure: 查询失败
    static func fetchTeamSyncCount(success: @escaping (Int) -> Void, failure: ((Error?) -> Void)? = nil) {
        WmcPreferenceSettingsManager.fetchTeamSyncConfig { list in
            var count = 0
            list.forEach { item in
                if item.isSync {
                    count += 1
                }
            }
            success(count)
        } failure: { error in
            failure?(error)
        }
    }

    /// 查询同步配置
    /// - Parameters:
    ///   - success: 配置
    ///   - failure: 查询失败
    static func fetchTeamSyncConfig(success: @escaping ([WmcMediaAlbumConfigurationModel]) -> Void, failure: ((Error?) -> Void)? = nil) {
        WmcMediaTeamManagerAPI.fetchConfiguration { list in
            WmcPreferenceSettingsManager.shared.syncCongigList = list
            success(list)
        } failure: { error in
            failure?(error)
        }
    }

    /// 从本地缓存中查询同步配置，如果没缓存的话请求接口查询
    /// - Parameters:
    ///   - success: 配置
    ///   - failure: 查询失败
    static func queryTeamSyncConfigCache(success: @escaping ([WmcMediaAlbumConfigurationModel]) -> Void, failure: ((Error?) -> Void)? = nil) {
        if let cache = WmcPreferenceSettingsManager.shared.syncCongigList, !cache.isEmpty {
            success(cache)
            return
        }
        WmcPreferenceSettingsManager.fetchTeamSyncConfig { list in
            success(list)
        } failure: { error in
            failure?(error)
        }
    }

    /// 创建团队后记录下来
    /// - Parameter model: model
    static func addTeamSyncConfig(model: WmcMediaAlbumConfigurationModel) {
        if let cache = WmcPreferenceSettingsManager.shared.syncCongigList {
            let isContains = cache.contains { item in
                return item.albumId == model.albumId
            }
            if !isContains {
                WmcPreferenceSettingsManager.shared.syncCongigList?.append(model)
            }
        } else {
            WmcPreferenceSettingsManager.shared.syncCongigList = [model]
        }
    }

    /// 退出团队
    /// - Parameter model: model
    static func removeTeamSyncConfig(model: WmcMediaAlbumConfigurationModel) {
        let idx = WmcPreferenceSettingsManager.shared.syncCongigList?.firstIndex(where: { item in
            item.albumId == model.albumId
        })
        if let idx = idx {
            WmcPreferenceSettingsManager.shared.syncCongigList?.remove(at: idx)
//            WmcUploadQueueManager.cleanInvalidTask()
        }
    }

    /// 更新团队配置
    /// - Parameter model: model
    static func updateTeamSyncConfig(model: WmcMediaAlbumConfigurationModel) {
        let idx = WmcPreferenceSettingsManager.shared.syncCongigList?.firstIndex(where: { item in
            item.albumId == model.albumId
        })
        if let idx = idx {
            WmcPreferenceSettingsManager.shared.syncCongigList?[idx] = model
        }
    }

    /// 加载相机设置
    func loadCameraSettings() {
        if let _cameraSettingJson: [String: Any] = WmcUserdefault.object(forKey: .Data.cameraSetting),
           let model: WmcPreferenceCameraSettingsModel = .deserialize(from: _cameraSettingJson)
        {
            cameraSetting = model
        }
    }
    
    private func isNeedUpload(configList: [WmcMediaAlbumConfigurationModel]) -> Bool {
        var result: Bool = false
        for (_, item) in configList.enumerated() {
            if item.isSync {
                result = true
                break
            }
        }
        return result
    }
}
